package cc.rengu.igas.channel.xmup.common.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

public class SignUtil {

    /**
     * 文件摘要：使用标准SHA-256算法计算摘要得byte数组，将byte数组转16进制大写字符输出
     *
     * @return
     */
    public static String genDigestBySha256(File fileName) {
        FileInputStream file = null;
        String sign = null;

        try {
            //指定摘要算法
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            file = new FileInputStream(fileName);
            int bytesRead = 0;
            byte[] bytesBuffer = new byte[1024];
            while ((bytesRead = file.read(bytesBuffer)) != -1) {
                messageDigest.update(bytesBuffer, 0, bytesRead);
            }
            //摘要byte数组
            byte[] data = messageDigest.digest();
            sign = byte2hex(data);
        } catch (Exception e) {

        } finally {
            try {
                file.close();
            } catch (IOException e) {

            }
        }
        return sign;
    }

    /**
     * 字符串摘要：使用标准SHA-256算法计算摘要得byte数组，将byte数组转16进制大写字符输出
     *
     * @return
     */
    public static String genDigestBySha256(String data) throws Exception {
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
        sha256.update(data.getBytes());
        return byte2hex(sha256.digest());
    }


    /**
     * 将byte数组转为16进制字符串并将所有字符转成大写输出
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int i = 0; i < b.length; i++) {
            stmp = Integer.toHexString(b[i] & 0xFF);
            if (stmp.length() == 1)
                hs += "0" + stmp;
            else
                hs += stmp;
        }
        return hs.toUpperCase();
    }
}